﻿using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// health value plus toast
/// </summary>
public class NumShowToast : MonoBehaviour
{
    public UnityEngine.UI.Text numText;
    Outline m_TextOutline;

    bool m_InShowing;

    ZTransformAnim m_ZTransformAnim;
    ZTransformAnim zTransformAnim
    {
        get
        {
            if (m_ZTransformAnim == null)
                m_ZTransformAnim = gameObject.AddComponent<ZTransformAnim>();

            return m_ZTransformAnim;
        }
    }
    ZUIAnimTools m_ZUIAnimTools;
    ZUIAnimTools zUIAnimTools
    {
        get
        {
            if (m_ZUIAnimTools == null)
                m_ZUIAnimTools = gameObject.AddComponent<ZUIAnimTools>();

            return m_ZUIAnimTools;
        }
    }

    int m_CurValue;

    public float showTime = 1;

    public AnimationCurve scaleCurve = AnimationCurve.EaseInOut(0,0,1,1);

    Vector3 m_TextStartPos;

    public Vector3 moveVec = new Vector3(0,20,0);

    int m_Seq;

    public string prex = "+ ";

    private void Start()
    {
        m_TextStartPos = numText.transform.localPosition; 
        m_TextOutline = numText.GetComponent<Outline>();
    }

    public void Show(int value)
    {
        if (m_InShowing)
        {
            m_CurValue += value;
        }
        else
        {
            m_InShowing = true;

            m_CurValue = value;
        }
        m_Seq++;

        int curSeq = m_Seq;

        this.numText.text = prex + Mathf.Abs(m_CurValue);

        numText.transform.localScale = .5f * Vector3.one;
        numText.transform.localPosition = m_TextStartPos;
        if (m_TextOutline)
        {
            m_TextOutline.enabled = true; ;
        }

        zUIAnimTools.UIAlpha(numText.rectTransform, 1, .1f);

        zTransformAnim.ScaleTo(numText.transform, Vector3.one, .2f, () =>
        {
            DoActionDelay.DelayAction(showTime / 2, () =>
            {
                CheckEnd(curSeq);
            });
        });
    }

    void CheckEnd(int seq)
    {
        if (seq == m_Seq)
        {
            m_InShowing = false;

            float fadeOutTime = showTime / 2;

            zTransformAnim.MoveTo(numText.transform, numText.transform.localPosition + moveVec, fadeOutTime, null,true);

            DoActionDelay.DelayAction(fadeOutTime - .12f, () =>
            {
                zUIAnimTools.UIAlpha(numText.rectTransform, 0, .12f);

                if (m_TextOutline)
                {
                    m_TextOutline.enabled = false;
                }
            });
        }
    }
}